<template>
	<view class="content">
		<!-- 弹出层遮罩层 -->
		<view class="bg" v-if="isFocus"></view>
		<!-- 返回栏 -->
		<view class="header-nav">
			<!-- <view class="status_bar"></view> -->
			<statusBar></statusBar>
			<!-- 自定义状态栏 -->
			<view class="status_title">
				<view class="status_left">
					<image class="" src="@/static/go-back.svg" mode="widthFix" @click="goBack"></image>
					<view class="status_header">
						<image :src="postDetails.data.avatarUrl" mode="widthFix"></image>
						<text>{{postDetails.data.nickName}}</text>
					</view>
				</view>
				<view class="status_right" >
					<view v-if="!postDetails.data.isInterest" type="default" @click="changeAttention">关注</view>
					<view v-else type="default" class="followed" @click="changeAttention">已关注</view>
					<image class="" src="@/static/share.svg" mode="widthFix" @click="toShare"></image>
				</view>
			</view>
		</view>

		<view class="content-right">
			<view class="swiper">
				<swiper :indicator-dots="true" :interval="3000" :duration="1000">
					<swiper-item v-for="item in postDetails.data.banner" :key="item">
						<view class="swiper-item">
							<image
								:src="item">
							</image>
							<view class="try-it-on">
								<image src="../../static/AR2.svg"/>
								<text>AR试戴</text>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</view>
			<view class="content-aside">
				<view class="content-title">
					{{postDetails.data.title}}
				</view>
				<view class="content-sub-title">
					{{postDetails.data.content}} <text v-for="item in postDetails.data.topicId" :key="item.id">#{{item.content}}</text>
				</view>
				<view class="content-ip">
					编辑于{{postDetails.data.updatedTime}} {{postDetails.data.ipAddress}}
				</view>
				<view class="content-reviews">
					<CComment ref="ccRef" 
						v-model:userInfo="userInfo" 
						v-model:tableData="tableData"
						v-model:tableTotal="tableTotal" 
						@likeFun="likeFun" 
						@replyFun="replyFun" 
						@deleteFun="deleteFun"
						:deleteMode="deleteMode"
						@myReply="myReply"
					></CComment>
				</view>
			</view>
		</view>
		<!-- 底部回复框 -->
		<view class="comment-view"> 
			<view class="comment-top">
				<view class="comment-left" :class="{'is-focus':isFocus}">
					<view @click.stop="toSend">发送</view>
					<input :placeholder="placeholderVal" :focus="isFocus" ref="inputRef" v-model="inputVal" @focus="inputFocus" @blur="inputBlur"/>
					<!-- <input placeholder="留下你的评论吧～" :focus="isFocus" ref="inputRef" v-model="inputVal" @focus="inputFocus"/> -->
					<view class="send" v-if="isFocus">
						<image src="../../static/aite.svg" />
						<!-- <view @touchstart.stop="toSend">发送</view> -->
						<view @click.stop="toSend">发送</view>
					</view>
				</view>
				
				<view class="comment-right" v-if="!isFocus">
					<view @click="changeLike">
						<image v-if="postDetails.data.isLike" src="../../static/like.svg" />
						<image v-else src="../../static/abreast-no-like.svg" />
						<text>{{functions.exchangeUnit(postDetails.data.likes || 0)}}</text>
					</view>
					<view @click="changeCollect">
						<image v-if="postDetails.data.isCollection" src="../../static/collect.svg" />
						<image v-else src="../../static/no-collect.svg" />
						<text>{{functions.exchangeUnit(postDetails.data.collection || 0)}}</text>
					</view>
					<view>
						<image src="../../static/msg.svg" />
						<text>{{functions.exchangeUnit(postDetails.data.comments || 0)}}</text>
					</view>
				</view>
			</view>
			<view class="safe-padding" v-if="!isFocus"></view>
		</view>

		<!-- 分享弹框 -->
		<popupShare ref="popupShareRef" :id="0" :dataInfo="dataInfo"></popupShare>
		<!-- 举报弹框 -->

	</view>
</template>

<script setup>
	import CComment from "@/components/cc-comment/index";
	import { onLoad,  onShow } from "@dcloudio/uni-app";	
	import { ref,reactive,onMounted,nextTick,computed } from 'vue'
	import { articleDetail,commentsPages,artSaveLike,artSaveCollect, commentsInsert, commentsDelete,commentsSaveLike } from '@/api/posting.js'
	import { collectionUser } from '@/api/user.js'
	import functions from '@/utils/functions.js'
	// 唤起新评论弹框
	let ccRef = ref(null);

	/* ================================评论相关 */
	// 点赞回调事件
	const likeFun = async ({ params }, callback) => {
		console.log("likeFun", params.is_like);
		// **************************当请求失败, 调用callback重置点赞效果;
		// Demo如下:
		// axios.post("http://xxx/like", { id: params }).then((res) => {
		//   if (res.code !== 0) {
		//     callback(res);
		//   }
		// });

		try {
			let res = await commentsSaveLike({
				dataId:params.id,
				status: params.is_like ? 1 : 2,  //1点赞  2 取消点赞
				type:2    	//类型:1帖子,2评论
			})
			uni.showToast({
				title: params.is_like ? '点赞成功' : '已取消点赞',
				icon:'none'
			});
		} catch (error) {
			console.log('点赞报错error',error)
			callback();
		}
	}

	// 评论回调事件
	const replyFun = ({ params }, callback) => {
		console.log("replyFun", params);
		// **************************当请求成功, 调用callback执行评论插入;
		// Demo如下:
		// axios.post("http://xxx/reply", { ...params }).then((res) => {
		//   if (res.code === 0) {
		//     callback(res);
		//   }
		// });
		const res = {
			id: Math.random()
		}; // 很重要的回参! 必须拿到后端返回评论id! 删除需要!
		setTimeout(() => callback(res), 500); // 目前为了展示效果, 直接执行callback



	}

	/** 删除回调事件
	 * mode 删除模式
	 * -- bind: 当被删除的一级评论存在回复评论, 那么该评论内容变更显示为[当前评论内容已被移除]
	 * -- only: 仅删除当前评论(后端删除相关联的回复评论, 否则总数显示不对)
	 * -- all : 删除所有评论包括回复评论
	 */
	const deleteMode = ref("all");
	const openComment = () => {
		ccRef.value.newCommentFun();
	}
	const deleteFun = async ({ params, mode }, callback) => {
		console.log("deleteFun", {
			params,
			mode
		});
		// **************************当请求成功, 调用callback执行评论删除;
		switch (deleteMode) {
			case "bind":
				// 逻辑: 调用接口进行评论内容修改 update
				setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
				break;
			case "only":
				// 逻辑: 调用接口删除一个评论 delete
				setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
				break;
			default:
				// all
				// 逻辑: 调用接口删除多个评论 [delete]
				// Demo如下:
				// axios.post("http://xxx/delete", { ids: params }).then((res) => {
				//   if (res.code === 0) {
				//     callback(res);
				//   }
				// });
				let res = await commentsDelete({id:params[0]})
				uni.showToast({
					title: '删除成功',
					icon:'none'
				});
				callback(res);
				break;
		}
	}

	// ----模拟数据------模拟数据------模拟数据----
	// 作者信息(提示: 一般来自localstorage, 如果是实时获取的话, 那么获取到数据后再v-if显示评论组件)
	let userInfo = ref({
		id: 3, //  用户id
		user_name: "李清照", // 用户名
		user_avatar: "https://pic1.zhimg.com/80/v2-a79071a705f55c5d88f6c74e6111fe84_720w.webp", // 用户头像
	});
	let tableTotal = ref(0); // 评论总数
	// let tableData = ref([{
	// 		id: 120, // 评论id
	// 		parent_id: null, // 父级评论id  就是第一层的那条评论id
	// 		reply_id: null, // 被回复人评论id
	// 		reply_name: null, // 被回复人名称
	// 		user_name: "ikun", // 用户名
	// 		user_avatar: "https://pic1.zhimg.com/80/v2-a79071a705f55c5d88f6c74e6111fe84_720w.webp", // 评论者头像地址
	// 		user_content: "唱,跳,rap,篮球", // 评论内容
	// 		is_like: false, // 是否点赞
	// 		like_count: 120, // 点赞数统计
	// 		create_time: "2024-01-01 09:16", // 创建时间
	// 	},
	// 	{
	// 		id: 130,
	// 		parent_id: 120, // 评论的父级id
	// 		reply_id: 120, // 被回复评论id
	// 		reply_name: "ikun", // 被回复人名称
	// 		user_name: "小黑子", // 用户名
	// 		user_avatar: "https://pic2.zhimg.com/80/v2-06eade66ec837713d765b1557bf20b25_720w.webp", // 评论者头像地址
	// 		user_content: "姬霓太美", // 评论内容
	// 		is_like: false, // 是否点赞
	// 		like_count: 67, // 点赞数统计
	// 		create_time: "2024-01-01 17:06", // 创建时间
	// 	},
	// 	{
	// 		id: 140,
	// 		parent_id: 120, // 评论的父级id
	// 		reply_id: 130, // 被回复评论id
	// 		reply_name: "小黑子", // 被回复人名称
	// 		user_name: "守护宗主维护宗门", // 用户名
	// 		user_avatar: "https://pic3.zhimg.com/80/v2-244696a62fa750b8570cf56bfaa5b26a_720w.webp", // 评论者头像地址
	// 		user_content: "你露出鸡脚了", // 评论内容
	// 		is_like: false, // 是否点赞
	// 		like_count: 16, // 点赞数统计
	// 		create_time: "2024-01-02 23:08", // 创建时间
	// 	},
	// 	{
	// 		id: 150,
	// 		parent_id: null, // 评论的父级id
	// 		reply_id: null, // 被回复评论id
	// 		reply_name: null, // 被回复人名称
	// 		user_name: "音乐制作人", // 用户名
	// 		user_avatar: "https://pic2.zhimg.com/80/v2-88ec6f8c6d3305122664dd18a28730e5_720w.webp", // 评论者头像地址
	// 		user_content: "只因你太美baby 只因你太美baby 只因你实在是太美baby 只因你太美baby 迎面走来的你让我如此蠢蠢欲动 这种感觉我从未有 Cause I got a crush on you who you 你是我的 我是你的 谁 再多一眼看一眼就会爆炸 再近一点靠近点快被融化", // 评论内容
	// 		is_like: true, // 是否点赞
	// 		like_count: 8, // 点赞数统计
	// 		create_time: "2024-01-08 00:45", // 创建时间
	// 	},
	// ]); // 评论表

	let tableData = ref([]); //评论数据

	/* ================================评论相关结束 */

	//是否获取焦点
	const isFocus = ref(false)
	const inputRef = ref(null)
	//帖子id
	const postingId = ref(0)
	//帖子详情
	const postDetails = reactive({
		data:{}
	})
	const popupShareRef = ref(null)
	const dataInfo = reactive({})
	//评论输入框
	const inputVal = ref('')
	//回复框 回复的人的信息
	const myReplyTemp = reactive({
		status:1,  //当前是发送新评论状态还是回复别人的状态  1 新评论   2回复别人
		data:{}
	});

  const goBack = () => {
    uni.navigateBack({ delta: 1 })
  }
	onLoad(({id,isComment}) => {
		// console.log('option',option);
		postingId.value = Number(id)
		if(isComment){
			console.log('获取焦点')
			// inputFocus()
		}
	})
	onMounted(async () =>{
		getArticleDetail()
		getCommentsPages()
		// await nextTick()
		// console.log('inputRef.value',inputRef.value)
		// if(isFocus.value) inputRef.value.focus()
	})

	//帖子详情
	const getArticleDetail = async () => {
		let res = await articleDetail({id:postingId.value})
		console.log('帖子详情',res);
		postDetails.data = res
	}
	//评论分页
	const getCommentsPages = async () => {
		const datas = {
			articleId:postingId.value,
			page:1,
			pageSize:10,
			type:1,
			replyId:0
		}
		let res = await commentsPages(datas)
		console.log('评论',res.list);
		tableTotal.value = res.total
		let ressss = reconstructionData(res.list)
		console.log('ressss',ressss)
		tableData.value = ressss
	}

	// 评论数据重构
	const reconstructionData = (v) => {
		let newData = []
		v.forEach(item => {
			if(item.children && item.children.length>0){
				newData.push({
					id:item.id,
					parent_id:null,
					reply_id:item.replyId || null,
					reply_name:'',
					user_name:item.nickName,
					user_avatar:'https://pic1.zhimg.com/80/v2-a79071a705f55c5d88f6c74e6111fe84_720w.webp',
					user_content:item.content,
					is_like:item.isLike,
					like_count:functions.exchangeUnit(item.likes),
					// like_count:functions.exchangeUnit(10002),
					create_time:item.updatedTime || '2024-01-08 00:45',
					userId:item.userId ,//评论人id
					comCount:item.comCount ,//评论回复数量
				})
				item.children.forEach(item2 => {
					newData.push({
						id:item2.id,
						parent_id:item.id || null,
						reply_id:item2.replyId || null,
						reply_name:item2.replyNickName,
						user_name:item2.nickName,
						user_avatar:'https://pic1.zhimg.com/80/v2-a79071a705f55c5d88f6c74e6111fe84_720w.webp',
						user_content:item2.content,
						is_like:item2.isLike,
						like_count:functions.exchangeUnit(item2.likes),
						// like_count:functions.exchangeUnit(10002),
						create_time:item2.updatedTime || '2024-01-08 00:45',
						userId:item2.userId,//评论人id
					})
				})
			}else{
				newData.push({
					id:item.id,
					parent_id:null,
					reply_id:item.replyId || null,
					reply_name:'',
					user_name:item.nickName,
					user_avatar:'https://pic1.zhimg.com/80/v2-a79071a705f55c5d88f6c74e6111fe84_720w.webp',
					user_content:item.content,
					is_like:item.isLike,
					like_count:functions.exchangeUnit(item.likes),
					// like_count:functions.exchangeUnit(10002),
					create_time:item.updatedTime || '2024-01-08 00:45',
					userId:item.userId,//评论人id
					comCount:item.comCount ,//评论回复数量
				})
			}
		})
		return newData
	}

	//分享
	const toShare = () => {
		// console.log('popupShare.value',popupShare.value);
		popupShareRef.value.open('bottom')
	}

	//关注 取消关注作者
	const changeAttention = async () => {
		const res = await collectionUser({id:postDetails.data.dataId})
		uni.showToast({
			title: postDetails.data.isInterest ? '已取消关注' : '关注成功',
			icon:'none'
		});
		getArticleDetail()
		console.log('关注结果');
		
	}

	//帖子点赞
	const changeLike = async () => {
		let res = await artSaveLike({
			dataId:postingId.value,
			status: postDetails.data.isLike ? 2 : 1,  //1点赞  2 取消点赞
			type:1    	//类型:1帖子,2评论
		})
		uni.showToast({
			title: postDetails.data.isLike ? '已取消点赞' : '点赞成功',
			icon:'none'
		});
		getArticleDetail()
		console.log('点赞结果',res)
	}

	//帖子收藏
	const changeCollect = async () => {
		console.log('postingId.value',typeof(postingId.value));
		let res = await artSaveCollect({
			articleId:postingId.value,
			status: postDetails.data.isCollection ? 2 : 1  //1收藏  2 取消收藏
		})
		uni.showToast({
			title: postDetails.data.isCollection ? '已取消收藏' : '收藏成功',
			icon:'none'
		});
		getArticleDetail()
		console.log('收藏结果',res)
	}
	
	//发送评论
	const toSend = async () => {
		console.log('点击发送 inputVal',inputVal.value)
		console.log('myReplyTemp.data',myReplyTemp.data.item1)
		if(myReplyTemp.data.item1){
			//回复
			let datas = {
				artcleOwnerId:postDetails.data.dataId,
				articleId:postingId.value,
				content:inputVal.value,
				replyId:myReplyTemp.data.item2 ? myReplyTemp.data.item2.id : myReplyTemp.data.item1.id,
				type:1
			}
			let res = await commentsInsert(datas)
			inputVal.value = ''
			uni.showToast({
				title: '发送成功',
				icon:'none'
			});
			isFocus.value = false
			myReplyTemp.data = {}
			getCommentsPages()
		}else{
			let datas = {
				artcleOwnerId:postDetails.data.dataId,
				articleId:postingId.value,
				content:inputVal.value,
				replyId:0,
				type:1
			}
			let res = await commentsInsert(datas)
			inputVal.value = ''
			uni.showToast({
				title: '发送成功',
				icon:'none'
			});
			isFocus.value = false
			myReplyTemp.data = {}
			getCommentsPages()
		}
		
	}

	//评论框获取焦点
	const inputFocus = () => {
		isFocus.value = true
		// openComment()
		console.log('获取焦点',isFocus.value)
	}
	const inputBlur = () => {
		isFocus.value = false
		console.log('光标失焦',isFocus.value);
	}
	// 评论组件点击回复 事件
	const myReply = (replyTemp) => {
		console.log('myReply---replyTemp',replyTemp)
		myReplyTemp.data = replyTemp
		isFocus.value = true
	}
	//输入框  placeholder 的值
	const placeholderVal = computed(() => {
		let res = ''
		if(!myReplyTemp.data.item1) return '留下你的评论吧～'
		res = myReplyTemp.data.item2 ? `回复给${myReplyTemp.data.item2.user_name}` : `回复给${myReplyTemp.data.item1.user_name}`
		return res
	})

</script>

<style scoped lang="scss">
	.content{
		position: relative;
	}
	.bg{
		width: 100%;
		height: 100%;
		background: rgba(0,0,0,0.5);
		position: absolute;
		top: 0;
		right: 0;
		z-index: 98;
	}
	/* 自定义状态栏 */
	.header-nav {
		height: calc(var(--status-bar-height) + 44px);
		position: fixed;
		top: 0;
		z-index: 97;
		width: 100%;
	}

	.status_bar {
		height: var(--status-bar-height);
		width: 100%;
		background-color: #FFFFFF;
	}

	/* 自定义导航栏 */
	.status_title {
		box-sizing: border-box;
		display: flex;
		justify-content: space-between;
		align-items: center;
		width: 100%;
		height: 44px;
		padding: 0 16px;
		background-color: #FFFFFF;
	}

	.status_left {
		display: flex;
		align-items: center;

		.status_header {
			display: flex;
			align-items: center;

			image {
				width: 64rpx;
				height: 64rpx;
				border-radius: 50%;
				margin: 0 16rpx;
			}

			text {
				font-size: 24rpx;
				color: #111111;
				font-weight: 500;
			}
		}

		>image {
			width: 44rpx !important;
		}
	}

	.status_center {
		font-size: 17px;
		font-weight: 700;
	}

	.status_right {
		display: flex;
		align-items: center;

		view {
			width: 104rpx;
			height: 48rpx;
			background: #16DFF2;
			border-radius: 24rpx;
			font-weight: 500;
			font-size: 24rpx;
			color: #FFFFFF;
			line-height: 48rpx;
			text-align: center;
			margin-right: 16rpx;
			box-sizing: border-box;
		}
		.followed{
			background-color: white;
			color: #333333;
			border-radius: 24rpx;
			border: 2rpx solid #ADADAD;
		}

		image {
			width: 48rpx;
		}
	}

	.content-right {
		margin-top: calc(var(--status-bar-height) + 44px);
		padding-bottom: calc(env(safe-area-inset-bottom) + 116rpx);
	}

	.swiper {
		swiper {
			height: 800rpx;

			.swiper-item {
				height: 780rpx;
				position: relative;
				>image {
					width: 100%;
					height: 100%;
				}
				.try-it-on{
					position: absolute;
					left: 302rpx;
					bottom: 34rpx;
					width: 146rpx;
					height: 44rpx;
					background: #FFFFFF;
					border-radius: 22rpx;
					@include flex(row,center,center);
					>image{
						width: 36rpx;
						height: 36rpx;
						margin-right: 8rpx;
					}
					>text{
						font-weight: 400;
						font-size: 22rpx;
						color: #333333;
					}
				}
			}
		}
	}

	::v-deep .swiper .uni-swiper-dots {
		bottom: 0 !important;
	}

	::v-deep .swiper .uni-swiper-dot {
		width: 6px !important;
		height: 6rpx;
		border-radius: 6rpx;
		background: #E4E4E4;
	}

	::v-deep .swiper .uni-swiper-dot-active {
		width: 8px !important;
		height: 6rpx;
		border-radius: 4rpx;
		background: #2D2A3D;
	}

	.content-aside {
		padding: 30rpx;

		.content-title {
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			font-size: 34rpx;
			color: #333333;
			line-height: 34rpx;
			margin-bottom: 18rpx;
		}

		.content-sub-title {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			line-height: 44rpx;

			>text {
				color: #0BB1B0;
				padding-right: 10rpx;
			}
		}

		.content-ip {
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #A9A7B3;
			line-height: 24rpx;
			margin-top: 36rpx;
			margin-bottom: 60rpx;
		}
	}

	.comment-view{
		width: 750rpx;
		/* height: calc(); */
		
		position: fixed;
		bottom: 0;
		left: 0;
		z-index: 99;

		.safe-padding{
			background-color: rgb(255, 255, 255);
		}

		.comment-top{
			width: 750rpx;
			height: 110rpx;
			padding: 26rpx 20rpx;
			box-sizing: border-box;
			background: #ffffff;
			@include flex(row,space-between);

			.comment-left{
				width: 428rpx;
				height: 70rpx;
				position: relative;

				input{
					width: 100%;
					height: 70rpx;
					background: #F4F3F7;
					border-radius: 34rpx;
					padding-left: 24rpx;
					box-sizing: border-box;
					color: #707070;
					font-size: 26rpx;
					transition: all .3s linear;
				}
				.is-focus{
					width: 690rpx;
				}

				.send{
					width: 160rpx;
					height: 70rpx;
					position: absolute;
					right: 6rpx;
					top: 0;
					@include flex(row,space-between);

					image{
						width: 40rpx;
						height: 40rpx;
						/* margin-right: 32rpx; */
					}

					view{
						width: 88rpx;
						height: 58rpx;
						background: #16DFF2;
						border-radius: 28rpx;
						font-weight: 400;
						font-size: 26rpx;
						color: #FFFFFF;
						line-height: 58rpx;
						text-align: center;
					}
				}
			}
			.is-focus{
				width: 690rpx;
			}


			::v-deep .input-placeholder{
				font-weight: 400;
				font-size: 24rpx;
				color: #A9A7B3;
			}
			.comment-right{
				width: 220rpx;
				@include flex(row,space-between);
				>view{
					width: 50rpx;
					height: 68rpx;
					@include flex(column,space-between);
					image{
						width: 40rpx;
						height: 40rpx;
					}
					text{
						font-weight: 400;
						font-size: 22rpx;
						color: #333333;
					}
				}
			}
		}


	}
</style>